package com.dx_society.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dx_society.domain.*;
import com.dx_society.dto.Result;
import com.dx_society.service.ActivitiesService;
import com.dx_society.service.ActivityMemberService;
import com.dx_society.mapper.ActivityMemberMapper;
import com.dx_society.service.UserDetailService;
import com.dx_society.utils.UserHolder;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.dx_society.utils.RedisConstants.ACTIVITIES_LIST_TTL;
import static com.dx_society.utils.RedisConstants.AC_CODE_KEY;

/**
* @author 韶光善良君
* @description 针对表【dx_activity_member(活动报名表)】的数据库操作Service实现
* @createDate 2024-07-01 10:15:12
*/
@Service
public class ActivityMemberServiceImpl extends ServiceImpl<ActivityMemberMapper, ActivityMember>
    implements ActivityMemberService{

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    ActivitiesService activitiesService;

    @Resource
    UserDetailService userDetailService;
    @Override
    public Result joinActivities(Long id) {
        Long userId;
        try {
            userId = UserHolder.getUser().getUserid();
        } catch (Exception e) {
            return Result.fail("用户未登录");
        }
        QueryWrapper<ActivityMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ac_id", id);
        queryWrapper.eq("user_id", userId);
        ActivityMember activityMember = getOne(queryWrapper);
        // 检查是否存在
        if (activityMember == null) {
            // 不存在，创建新的关系，state改为0，填写入部原因
            activityMember = new ActivityMember();
            activityMember.setAcId(id);
            activityMember.setUserId(userId);
            activityMember.setUserName(UserHolder.getUser().getUsername());
            activityMember.setState(0);
            save(activityMember);
            // 缓存更新 报名人数变动
            activitiesService.saveActivities2Redis(ACTIVITIES_LIST_TTL);
            return Result.ok("活动已报名，请等待活动时进行签到");
        } else if(activityMember.getState() == 0){
            return Result.fail("您已报名");
        } else if(activityMember.getState() == 1){
            return Result.fail("您已参与");
        }else {
            return Result.fail("未知错误");
        }
    }

    @Override
    public Result signActivities(Long id, String signCode,Long userId) {

        // 从redis获取签到码
        String sCode = stringRedisTemplate.opsForValue().get(AC_CODE_KEY + id);
        if(!Objects.equals(sCode, signCode)){
            return Result.fail("签到码错误");
        }

        QueryWrapper<ActivityMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ac_id", id);
        queryWrapper.eq("user_id", userId);
        ActivityMember activityMember = getOne(queryWrapper);
        // 检查是否存在
        if (activityMember == null) {
            return Result.fail("您未报名");
        }else if(activityMember.getState() == 1){
            return Result.fail("您已签到");
        }else {
            // 签到成功包含：1、修改状态为1 2、修改综测分
            activityMember.setState(1);
            updateById(activityMember);

            // 获取该活动综测分
            Integer score = activitiesService.query().eq("ac_id", id).one().getAcScout();
            // 获取用户详情
            UserDetail userDetail = userDetailService.getById(userId);
            // 修改用户持有的综测分
            userDetail.setAcScore(userDetail.getAcScore()+score);
            userDetailService.saveOrUpdate(userDetail);
            return Result.ok("签到成功");
        }
    }

    @Override
    public Result queryMyActivitiesList(Integer state) {
        Long userId;
        try {
            userId = UserHolder.getUser().getUserid();
        } catch (Exception e) {
            return Result.fail("用户未登录");
        }
        List<ActivityMember> list = query().eq("user_id", userId).eq("state", state).list();
        List<Activities> activities = new ArrayList<>();
        for (ActivityMember activityMember : list) {
            activities.add(activitiesService.getById(activityMember.getAcId()));
        }
        if (list.isEmpty()) {
            return Result.fail("您没有加入任何活动");
        }
        return Result.ok(activities);
    }
}




